'''
rgeViews - for the Random Game Editor project            
By Oipo (kingoipo@gmail.com)

compression/decompression util functions

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
'''

import pylzma as CompressMethod #change to for example bz2 or pylzma if you want to change the compression method
import os

'''
    Note that all of the methods involving file compression/decompression
    first load the entire file into mem and then compress it in one shot.
    Depending on how big the file is, that may take quite a lot of mem.
'''

def compressFileToFile(filename):
    path = os.path.join("Modules", filename)
    outpath = os.path.join("Modules", filename + ".rgemod")

    print "compressing " + path + " into " + outpath

    if not os.path.isfile(path):
        print "file does not exist"
        return ""

    f = open(path, 'r')
    o = open(outpath, 'w')

    data = ""

    for line in f:
        data += line

    o.write(CompressMethod.compress(data))

    f.close()
    o.close()

    return filename + ".rgemod"

def decompressFileToFile(filename):
    path = os.path.join("Modules", filename)
    outpath = path[0:path.find(".rgemod")]

    print "decompressing " + path + " into " + outpath

    if not os.path.isfile(path):
        print "file does not exist"
        return ""

    f = open(path, 'r')
    o = open(outpath, 'w')

    data = ""

    for line in f:
        data += line

    o.write(CompressMethod.decompress(data))

    f.close()
    o.close()

    return outpath[outpath.find("/")+1:]

def compressMemToFile(filename, data):
    path = os.path.join("Modules", filename)

    print "compressing data into " + path

    o = open(path, 'w')
    o.write(CompressMethod.compress(data))
    o.close()

def decompressFileToMem(filename):
    path = os.path.join("Modules", filename)

    print "decompressing " + path + " into mem"

    if not os.path.isfile(path):
        print "file does not exist"
        return ""

    f = open(path, 'r')

    data = ""

    for line in f:
        data += line

    retdata = CompressMethod.decompress(data)

    f.close()

    return retdata

def compressString(string):
    return CompressMethod.compress(string)

def decompressString(string):
    return CompressMethod.decompress(string)

